﻿Imports System.Runtime.CompilerServices

Public Module Extensions

	<Extension()>
	Public Function ToPhrases(Text As String, FilterArray As List(Of String)) As List(Of TextSegment)
		Return SplitString(Text, FilterArray)
	End Function

	Private Function SplitString(Text As String, FilterArray As List(Of String)) As List(Of TextSegment)
		Dim returnList As New List(Of TextSegment)

		If Text.Length > 0 Then
			'add text as a segment and then proceed to split it
			returnList.Add(New TextSegment(Text, False))

			If FilterArray IsNot Nothing Then
				For Each item In FilterArray
					Dim i As Integer = 0
					Do While i < returnList.Count
						Dim workingText As String = returnList(i).Text
						Dim lowerItem As String = item.ToLowerInvariant
						Dim lowerText As String = workingText.ToLowerInvariant
						If lowerText.Contains(lowerItem) AndAlso Not returnList(i).IsBold Then
							If lowerText = lowerItem Then
								'we have a match for the entire item
								Return returnList
							End If

							'we have to bold something
							Dim part1 As String = workingText.Substring(0, lowerText.IndexOf(lowerItem))
							Dim part2 As String = workingText.Substring(lowerText.IndexOf(lowerItem), lowerItem.Length)
							Dim part3 As String = workingText.Substring(lowerText.IndexOf(lowerItem) + lowerItem.Length, lowerText.Length - lowerText.IndexOf(lowerItem) - lowerItem.Length)

							'move the space to the bolded item
							'this makes sizing easier later on
							If part3.Length > 0 AndAlso part3(0) = " " Then
								part2 &= " "
								part3 = part3.Substring(1, part3.Length - 1)
							End If

							'remove the entry we're working on and add in these new ones in reverse order
							returnList.RemoveAt(i)
							returnList.Insert(i, New TextSegment(part3, False))
							returnList.Insert(i, New TextSegment(part2, True))
							returnList.Insert(i, New TextSegment(part1, False))

						End If

						'move to next segment
						i += 1
					Loop
				Next
			End If
		End If

		Return returnList.Where(Function(x) x.Text.Length > 0).ToList
	End Function


End Module
